package com.campus_information_portal.controller;
import com.campus_information_portal.entity.Material;
import com.campus_information_portal.service.MaterialService;
import com.campus_information_portal.util.Message;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
@RequestMapping("/material")
@ResponseBody
@CrossOrigin(origins = "*")
public class MaterialController {
    @Autowired
    private MaterialService materialService;

    /**
     * @Describe: 上传文件并将信息保存在数据库中
     * @Author: 20155878 鄢前州
     * @Creat_date: 22:21
     * @Creat_time: 2018/6/1
     **/
    @RequestMapping(value = "/upPic", method = RequestMethod.POST)
    public Message addMaterial(@RequestParam("file") CommonsMultipartFile[] files, HttpServletRequest request) {
        System.out.println("==================Start============");
        Message flag = new Message();
        for (int i = 0; i < files.length; i++) {
            System.out.println("fileName---------->" + files[i].getOriginalFilename());
            if (!files[i].isEmpty()) {
                int pre = (int) System.currentTimeMillis();
                try {
                    //创建封装上传文件信息的资料类
                    Material material = new Material();
                    //获取文件的类型
                    String OriginalFilename = files[i].getOriginalFilename();
                    String fileSuffix = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
                    System.out.println("文件后缀：" + fileSuffix);
                    Integer materialTypeId = Integer.valueOf(materialService.querymaterial_type_idsBymaterial_typeName(fileSuffix));
                    System.out.println("上传文件类型ID：" + materialTypeId);
                    //获取文件大小
                    //先以M为单位，如果小于1M就以KB为单位
                    String filesize;
                    Long initilFileSize = files[i].getSize() / (1024);
                    if (initilFileSize > 1024) {
                        initilFileSize = initilFileSize / 1024;
                        filesize = Long.toString(initilFileSize) + "M";
                    } else {
                        filesize = Long.toString(initilFileSize) + "KB";
                    }
                    System.out.println("文件大小：" + filesize);
                    //获取文件上传时间
                    Date NowTime = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    String uptime = formatter.format(NowTime);
                    System.out.println("文件上传时间：" + uptime);
                    //获取唯一文件名
                    String uniqueFileName = new Date().getTime() + files[i].getOriginalFilename();
                    System.out.println("唯一文件名：" + uniqueFileName);
                    // 拿到输出流，同时重命名上传的文件
                    FileOutputStream os = new FileOutputStream("F:\\ideaWorkpPlace\\campus_information_portal\\service\\new\\campus_information_portal\\src\\updown\\" + uniqueFileName);
                    // 拿到上传文件的输入流
                    FileInputStream in = (FileInputStream) files[i].getInputStream();
                    // 以写字节的方式写文件
                    int b = 0;
                    while ((b = in.read()) != -1) {
                        os.write(b);
                    }
                    os.flush();
                    os.close();
                    in.close();
                    //保存上传文件信息
                    material.setMaterialTypeId(materialTypeId);
                    material.setTeInfoId(1);
                    material.setMaterialName(uniqueFileName);
                    material.setMaterialSize(filesize);
                    material.setMaterialUptime(uptime);
                    material.setMaterialDowntimes(0);
                    material.setMaterialState(0);
                    flag = materialService.addMaterial(material);
                    System.out.println("---------------------------");
                    int finaltime = (int) System.currentTimeMillis();
                    System.out.println(flag);
                    System.out.println(finaltime - pre);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    /**
     * @Method_name:
     * @Describe: 文件下载
     * @Author: 20155878 鄢前州
     * @Creat_date: 23:17
     * @Creat_time: 2018/6/1
     **/
    @RequestMapping(value = "/maretialDownload", method = RequestMethod.POST)
    public void download2(HttpServletRequest request, HttpServletResponse response, @Param("downMaterial_Name") String[] _downMaterial_Name) throws Exception {

        for (int i = 0; i < _downMaterial_Name.length; i++) {
            OutputStream out2 = null;
            System.out.println(_downMaterial_Name[i]);

        }
    }


    /**
     *
     * @Method_name:
     * @Describe: 查询全部上传资料
     * @Author: 20155878 鄢前州
     * @Creat_date: 23:18
     * @Creat_time: 2018/6/1
     **/
    @RequestMapping(value = "/queryAllMaterial", method = RequestMethod.GET)
    public Message queryAllMaterial(){
        Message flag=materialService.queryAllMaterial();
        System.out.println(flag);
        return flag;
    }
}
